package Reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//通过反射动态的创建对象
public class Test09 {

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        //获得class对象
        Class<?> c1 = Class.forName("Reflection.User");
        //构造一个对象
        User user = (User) c1.newInstance(); //本质上是调用了类的无惨构造器
        System.out.println(user);

        //通过构造器创建对象    , 是通过有参构造器来加载的
        Constructor<?> declaredConstructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
        User user2 =(User) declaredConstructor.newInstance("lidw", 1, 21);
        System.out.println(user2);

        System.out.println("=====通过反射调用普通方法====");
        User user3 = (User) c1.newInstance();
        //通过反射获取一个方法
        Method setName = c1.getDeclaredMethod("setName", String.class);
        setName.invoke(user3,"lihuaqi1"); //激活，传递一个对象，调用后面的值
        System.out.println(user3.getName());
        //通过反射操作属性
        User user4 = (User) c1.newInstance();
        Field name = c1.getDeclaredField("name"); //这里不能直接操作私有的属性
        name.setAccessible(true); //关闭了程序的安全监测 ,会降低程序执行的效率
        name.set(user4,"lihuaqi2");
        System.out.println(name.get(user4));

    }




}
